package com.cnswhy.cloud.server.system.controller;

import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.server.system.dto.UserPageDTO;
import com.cnswhy.cloud.server.system.dto.UserSaveDTO;
import com.cnswhy.cloud.server.system.dto.UserUpdateDTO;
import com.cnswhy.cloud.server.system.entity.LoginLog;
import com.cnswhy.cloud.server.system.entity.User;
import com.cnswhy.cloud.server.system.service.LoginLogService;
import com.cnswhy.cloud.server.system.service.SystemUserService;
import com.cnswhy.cloud.server.system.service.UserService;
import com.cnswhy.cloud.server.system.utils.AddressUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.github.zuihou.security.annotation.PreAuth;


/**
 * <p>
 * 前端控制器
 * 用户表
 * </p>
 *
 * @author cnswhy
 * @date 2020-10-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/user")
@Api(value = "User", tags = "用户表")
//@PreAuth(replace = "user:")
public class UserController extends SuperController<UserService, Long, User, UserPageDTO, UserSaveDTO, UserUpdateDTO> {
    @Autowired
    LoginLogService loginLogService;
    @Autowired
    SystemUserService systemUserService;
    @GetMapping("success")
    //@ControllerEndpoint(operation = "用户登录", exceptionMessage = "登录失败")
    public void loginSuccess(HttpServletRequest request) {
        String currentUsername = CnswhyUtil.getCurrentUsername();
        log.info(currentUsername);
        // update last login time
        systemUserService.updateLoginTime(currentUsername);
        // save login log
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(currentUsername);
        loginLog.setSystemBrowserInfo(request.getHeader("user-agent"));
        String ip = CnswhyUtil.getHttpServletRequestIpAddress();
        log.info("登录IP:{} 用户:{}", ip, currentUsername);

        loginLog.setIp(ip);
        loginLog.setLocation(AddressUtil.getCityInfo(ip));
        loginLogService.save(loginLog);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<User> userList = list.stream().map((map) -> {
            User user = User.builder().build();
            //TODO 请在这里完成转换
            return user;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(userList));
    }
}
